rm(list = ls())

library(tidyverse)
library(lfe)
library(readxl)
library(broom)
library(pbapply)

## Helper functions

source("code/helper_functions.R")

## Load data

btw <- readRDS("data/data_main.RDS") %>%
    dplyr::select(
        county_id_2018,
        year,
        matches("zweit|diff"),
        treat_categorical4, matches("covar")
    )

## Get the treatment from separate file

treat <- read_rds("data/spillover_treat.rds") %>%
    mutate(year = as.numeric(year))


## Merge

btw <- btw %>%
    left_join(treat)

## Def outcomes

outcomes <- c(
    "small_party_zweit_diff",
    "polar_bund_alt_diff"
)

## Def covariates

covars <- c(
    "covar_pop_total_diff",
    "covar_gdp_pc_diff"
)

## Code never experience exit or any change

btw <- btw %>%
    group_by(county_id_2018) %>%
    mutate(
        never_exit = ifelse(!any(treat_categorical4 == "Decrease",
            na.rm = T
        ), 1, 0),
        never_any_change = ifelse(all(treat_categorical4 == "NoChange",
            na.rm = T
        ), 1, 0)
    ) %>%
    ungroup()

## Subset to places w/ never_exit=1

btw <- btw %>%
    filter(never_exit == 1)

##

res <- pblapply(outcomes, function(o) {
    ## Get DF

    df_temp <- btw

    ## Prep

    df_temp$outcome <- df_temp %>% pull(!!o)
    df_temp <- df_temp %>%
        filter(!is.na(outcome) & !is.na(treat_neighbor)) %>%
        dplyr::select(
            outcome, year, county_id_2018,
            exit_neighbor,
            entry_neighbor,
            entry_and_exit_neighbor,
            treat_neighbor,
            one_of(covars)
        )

    ## Estimate

    m1 <- felm(outcome ~ exit_neighbor | year | 0 | county_id_2018,
        data = df_temp
    ) %>%
        tidy_felm() %>%
        mutate(fe = "year")

    ## Year + covars

    f <- paste0(
        "outcome ~ exit_neighbor  +",
        paste0(covars, collapse = "+"),
        "| year | 0 | county_id_2018"
    ) %>%
        as.formula()

    m2 <- felm(f, data = df_temp) %>%
        tidy_felm() %>%
        mutate(fe = "year_covars")

    rbind(m1, m2) %>%
        mutate(outcome = !!o)
}) %>%
    reduce(rbind) %>%
    mutate(period = "now") %>%
    filter(!str_detect(term, "Intercept|covar"))

## Remove some terms

res <- res %>%
    filter(!str_detect(term, "Intercept|covar"))

## Prep for plot

res <- res %>%
    mutate(outcome = str_remove(outcome, "_zweit")) %>%
    mutate(fe = dplyr::recode(fe,
        `year` = "Year FE",
        `year_covars` = "Covars + Year FE"
    )) %>%
    mutate(fe = factor(fe, levels = c(
        "Year FE",
        "Covars + Year FE"
    ))) %>%
    mutate(period_numeric = dplyr::recode(period,
        `lag1` = 2,
        `lag2` = 3,
        `now` = 1,
        `lead1` = -1,
        `lead2` = -2
    )) %>%
    mutate(
        conf.low90 = estimate - qnorm(0.95) * std.error,
        conf.high90 = estimate + qnorm(0.95) * std.error
    )



## Rename

res <- res %>%
    mutate(outcome = dplyr::recode(outcome,
        `polar_bund_alt_diff` = "polar_bund_diff",
    ))

## PD

pd <- position_dodge(0.4)

## Prep for plotting

res_plot <- res %>%
    filter(period_numeric == 1) %>%
    mutate(outcome = dplyr::recode(outcome,
        `small_party_diff` = "Small party vote share",
        `polar_bund_diff` = "Polarization"
    ))

## Figure A15

p1 <- ggplot(
    res_plot,
    aes(fe, estimate)
) +
    geom_hline(yintercept = 0, linetype = "dotted") +
    geom_errorbar(aes(ymin = conf.low90, ymax = conf.high90),
        position = pd, width = 0, linewidth = 1
    ) +
    geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
        position = pd, width = 0, linewidth = 0.5
    ) +
    geom_point(
        position = pd,
        shape = 21, fill = "white",
        size = 3
    ) +
    facet_wrap(~outcome, scales = "free_y", ncol = 2) +
    theme(legend.position = "bottom") +
    theme_bw() +
    xlab("") +
    ylab("Effect of newspaper exit\nin neighboring county") +
    theme(legend.position = "bottom")
p1


